package com.roc.web.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.MerinfoSearchBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.OperRole;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitPercent;
import com.roc.pojo.TblArea;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblOrgMain;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IRoleService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.agent.IAgentInfoService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;

@Component
@Scope("prototype")
@Namespace("/query")
public class OperatorQueryAction extends PaginationBaseAction{

	private Logger logger=LogManager.getLogger(OperatorQueryAction.class);
	private OperatorQuerySearchCondition searchCondition;
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	private Map<String, String> roleList=new TreeMap<String,String>();
	private Operators oper;
	private String accountNo;
	private Operators agent;
	private Long id;
	private List<TblArea> areaList=new ArrayList<TblArea>();
	
	private String[] agentList;
	private String agentTo;
	private String areaId;
	
	@Autowired
	IorgService orgService;	
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IPowerInfoService powerInfoService;
	@Autowired
	IRoleService roleService;
	@Autowired
	IAgentInfoService agentInfoService;
	@Autowired 
	IMerchantServices merchantServices;

	@Action(value = "init", results = { @Result(name = "success", location = "/pages/operator/operator_query.jsp"),@Result(name = "error", location = "/error.jsp")
    })
	public String init() throws Exception{
	    try{
	    	Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

			if(!logingOperators.getRoleType().equals(Role.SYSTEM.getCode())&&!logingOperators.getRoleType().equals(Role.O_MANAGER.getCode())&&!logingOperators.getRoleType().equals(Role.AGENT.getCode())&&!logingOperators.getRoleType().equals(Role.OPERATORS_COMM.getCode())&&!logingOperators.getRoleType().equals(Role.OPERATORS_LEAD.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();
		}catch (Exception e) {
		addActionError("加载信息失败，请联系客服人员");
		logger.error(e.getMessage(),e);
		}
			
	   return SUCCESS;
    }
	//查询机构
	public void org() throws Exception{
		try{
			Operators loginOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			orgList=orgService.queryOrgList();
			Map<String, String> roleMap=ConfigProperties.getRoleTypeProperties();
			roleMap.remove(Role.MANAGER.getCode());
			roleMap.remove(Role.MARKET_DIRECT.getCode());
			roleMap.remove(Role.MARKET_LEAD.getCode());
			roleMap.remove(Role.FINANCE_COMM.getCode());
			roleMap.remove(Role.FINANCE_LEAD.getCode());
			roleMap.remove(Role.OPERATORS_LEAD.getCode());
			roleMap.remove(Role.SFB_AGENT.getCode());
			roleMap.remove(Role.MERCHANT.getCode());
			if(Role.O_MANAGER.getCode().equals(loginOperators.getRoleType())){
				roleMap.clear();
				roleMap.put(Role.MERCHANT.getCode(), Role.MERCHANT.getName());
				roleMap.put(Role.O_MANAGER.getCode(), Role.O_MANAGER.getName());
				roleMap.put(Role.AGENT_BUSS.getCode(), Role.AGENT_BUSS.getName());
				roleMap.put(Role.AGENT.getCode(), Role.AGENT.getName());
				roleMap.put(Role.OPERATORS_COMM.getCode(), Role.OPERATORS_COMM.getName());
			}else if(Role.MANAGER.getCode().equals(loginOperators.getRoleType())){
				roleMap.remove(Role.SYSTEM.getCode());
				roleMap.remove(Role.MANAGER.getCode());
			}else{
				if(!loginOperators.getRoleType().equals(Role.SYSTEM.getCode())&&!loginOperators.getOneagentid().equals("48502000")){
					roleMap.clear();
					roleMap.put(Role.O_MANAGER.getCode(), Role.O_MANAGER.getName());
					roleMap.put(Role.O_MANAGER.getCode(), Role.O_MANAGER.getName());
					roleMap.put(Role.AGENT_BUSS.getCode(), Role.AGENT_BUSS.getName());
					roleMap.put(Role.AGENT.getCode(), Role.AGENT.getName());
					roleMap.put(Role.OPERATORS_COMM.getCode(), Role.OPERATORS_COMM.getName());
				}
			}
			
			roleList=roleMap;	
		}
		catch (Exception e) {
			throw new Exception("加载信息失败，请联系客服人员");
		}
	}
		
			
	
	
	
	@Action(value = "queryOperators", 
			results = { @Result(name = "success", location = "/pages/operator/operator_query.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryOperators() throws Exception{
       
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		
		if(searchCondition==null){
			searchCondition=(OperatorQuerySearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new OperatorQuerySearchCondition();
			}
		}
		try {
			init(); 
			
			searchCondition.setOrg_code(logingOperators.getOneagentid());
			searchCondition.setOpId(String.valueOf(logingOperators.getId()));//id
			searchCondition.setCurrrentRoleType(logingOperators.getRoleType());//角色
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			}
			dealWithTheListSpecially(searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	@Action(value = "recover", 
			results = { @Result(name = "success", location = "/pages/operator/operator_query.jsp"),
			@Result(name = "error", location = "/operator_query.jsp")
    })
	public String recover() throws Exception {
		
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		try{
			powerInfoService.updateStatus(oper.getId(), "00", logingOperators.getAccountNo());
			logger.info("【"+logingOperators.getAccountNo()+"】"+"成功恢复了操作员状态");
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		
		return queryOperators();
		
	}
	
	@Action(value = "logOut", 
			results = { @Result(name = "success", location = "/pages/operator/operator_query.jsp"),
			@Result(name = "error", location = "/operator_query.jsp")
    })
	public String logOut() throws Exception {
		
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
			
			powerInfoService.updateStatus(oper.getId(), "02", logingOperators.getAccountNo());
			logger.info("【"+logingOperators.getAccountNo()+"】"+"成功注销了操作员状态");

		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}

		return queryOperators();
		
	}
	
	@Action(value = "delay", 
			results = { @Result(name = "success", location = "/pages/operator/operator_query.jsp"),
			@Result(name = "error", location = "/operator_query.jsp")
    })
	public String delay() throws Exception {
		
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		List<Long> operIdList=this.getMulti_sel();
		
		try{
			if(operIdList==null||operIdList.size()==0){
				addActionMessage("请选择要延长有效时间的账号");
				return queryOperators();
			}		
			int totals=powerInfoService.updateValitTime(operIdList, logingOperators.getAccountNo());
			
			addActionMessage("【"+logingOperators.getAccountNo()+"】"+"成功有效的延迟了【"+totals+"】"+"个"+"操作员");
			logger.info("【"+logingOperators.getAccountNo()+"】"+"成功有效的延迟了【"+totals+"】"+"个"+"操作员");
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}

		return queryOperators();
		
	}
	
	@Action(value = "modif", 
			results = { @Result(name = "success", location = "/pages/operator/operator_modif.jsp"),
			@Result(name = "error", location = "/operator_query.jsp")
    })
	public String modif() throws Exception{
		try{
			init();
			oper=powerInfoService.loadOperatorsById(id);
			if(oper.getRoleType().equals(Role.MARKET_DIRECT.getCode())||oper.getRoleType().equals(Role.MARKET_LEAD.getCode())){
				Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				List<TblOrgMain> inOrgMainList = powerInfoService.queryOrgMinByAgentId(oper.getId());
				if(!inOrgMainList.isEmpty()){
					oper.setInOrgMainList(inOrgMainList);
					oper.setAreaIdRole(inOrgMainList.get(0).getAreaId());
					oper.setOutOrgMainList(powerInfoService.queryNoOrgMinByAgentId(oper.getId(), inOrgMainList.get(0).getAreaId()));
					areaList=orgService.listAreaByOrgCode(logingOperators.getOrgCode());
				}else{
					areaList=orgService.listAreaByOrgCode("48502000");
				}
			}
			oper.setRoleName(roleList.get(oper.getRoleType()));

		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
		
	}
	
	@Action(value = "saveOperator", 
			results = { @Result(name = "success", location = "/pages/operator/operator_query.jsp"),
			@Result(name = "error", location = "/operator_query.jsp")
    })
	public String saveOperator() throws Exception{
		
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Operators tempOper=null;
		
		try{
			tempOper=powerInfoService.loadOperatorsById(oper.getId());	
	    	if(logingOperators.getRoleType().equals(Role.SYSTEM.getCode())){
	    		if(Role.MARKET_DIRECT.getCode().equals(tempOper.getRoleType())||Role.MARKET_LEAD.getCode().equals(tempOper.getRoleType())){
	    			if("-1".equals(areaId)){
	    				tempOper.setAreaIdRole("-1");
	    			}else{
	    				if(StringUtils.isEmpty(agentTo)){
	    					addActionMessage("请选择管理代理商");
	    				}else{
	    					List<OperRole> operRoleList = new ArrayList<OperRole>();
	    					String[] agentStr = agentTo.split(",");
		    				for(int i=0;i<agentStr.length;i++){
		    					OperRole operRole = new OperRole();
		    					operRole.setAgentId(agentStr[i]);
		    					operRole.setAreaCode(areaId);
		    					operRole.setInsCode(tempOper.getOrgCode());
		    					operRoleList.add(operRole);
		    				}
		    				tempOper.setOperRoleList(operRoleList);
	    				}
	    			}
	    		}
	    	}
			powerInfoService.editUpdateOperator(dealSave(tempOper,oper),logingOperators.getAccountNo());
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return queryOperators();
		
	}
	@Action(value = "agentDetailed", 
			results = { @Result(name = "success", location = "/pages/operator/agent_list.jsp"),
			@Result(name = "error", location = "/operator_query.jsp")
    })
	public String agentdetailed() throws Exception{
		
		try{
			org();
			agent=agentInfoService.queryAgentInfo(accountNo);
			// 页面分润比例转化,分润比例 * 100
			List<ProfitPercent> perList = getNewPreList(agent.getProfitPerList());
			agent.setProfitPerList(perList);
			
			agent.setAgentName(ConfigProperties.getAgentType(agent.getAgentType()));
			for(TblInsInf bean:orgList){
				if(agent.getOrgCode().equals(bean.getInsIdCd())){
					agent.setOrgName(bean.getInsName());
				}
			}
			agent.setRoleName(roleList.get(agent.getRoleType()));
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		return SUCCESS;
		
	}
	@Action(value = "otherDetailed", 
			results = { @Result(name = "success", location = "/pages/operator/operator_list.jsp"),
			@Result(name = "error", location = "/operator_query.jsp")
    })
	public String otherdetailed() throws Exception{
		
		try{
			org();
			oper=agentInfoService.queryAgentInfo(accountNo);
			for(TblInsInf bean:orgList){
				if(oper.getOrgCode().equals(bean.getInsIdCd())){
					oper.setOrgName(bean.getInsName());
				}
			}
			oper.setRoleName(roleList.get(oper.getRoleType()));
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		return SUCCESS;
		
	}
	
	@Action(value = "resetPwd", 
			results = { @Result(name = "success", location = "/pages/operator/operator_query.jsp"),
			@Result(name = "error", location = "/operator_query.jsp")
    })
	public String resetPwd() throws Exception{
	
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		//if(logingOperators.getRoleType().equals(Constance.MERCHANT_TYPE_ADMIN)||logingOperators.getRoleType().equals(Constance.MERCHANT_TYPE_SYSTEM)||logingOperators.getRoleType().equals(Constance.MERCHANT_TYPE_ODAN))
		List<Long> operIdList=this.getMulti_sel();
		if(operIdList.size()==0||operIdList==null){
			addActionMessage("请选择要重置密码的账号");
			return queryOperators();
		}
		
		try{
			
			for (int i=0;i<operIdList.size();i++){
				long id =	operIdList.get(i);
				powerInfoService.resetPwd(logingOperators, id);
			}
			//id=this.getMulti_sel().get(0);
			addActionMessage("【"+logingOperators.getAccountNo()+"】"+"成功重置了【"+operIdList.size()+"】"+"个"+"操作员密码");
//			if(logingOperators.getRoleType().equals(Constance.MERCHANT_TYPE_ADMIN)){
//				
//			}else if(logingOperators.getRoleType().equals(Constance.MERCHANT_TYPE_SYSTEM)){
//				addActionMessage("系统管理员【"+logingOperators.getAccountNo()+"】"+"密码重置成功");
//
//			}else if(logingOperators.getRoleType().equals(Constance.MERCHANT_TYPE_ODAN)){
//				addActionMessage("O单管理员【"+logingOperators.getAccountNo()+"】"+"密码重置成功");
//
//			}
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		return queryOperators();
	}
	
	
 protected void dealWithTheListSpecially(List<Object> list) {
    	/*List<Object> tempList=new ArrayList<Object>();
		for(Object obj:list){
			Operators temp=(Operators)obj;
			for(TblInsInf bean:orgList){
				if(temp.getOrgCode().equals(bean.getInsIdCd())){
					temp.setOrgName(bean.getInsName());
				}
			}
			temp.setRoleName(roleList.get(temp.getRoleType()));
			tempList.add(temp);
		}
		searchRsList=tempList;*/
	 List<Object> tempList=new ArrayList<Object>();
	 if(null!=list && list.size()>0){
		 Iterator<?> iterator = list.iterator();
			while (iterator.hasNext()) {
				Object[] obj = (Object[]) iterator.next();
				Operators msb = new Operators();
				msb.setId(Long.parseLong(obj[0].toString()));
				msb.setAccountNo(obj[1].toString());
				if(obj[2]!=null){
					msb.setRealName(obj[2].toString());
				}
				if(obj[3]!=null){
					msb.setSex(obj[3].toString());
				}
				msb.setMobile(obj[4].toString());
				msb.setRoleName(roleList.get(obj[5].toString()));
				msb.setRoleType(obj[5].toString());
				if(obj[6]!=null){
					msb.setCardNo(obj[6].toString());
				}
				msb.setStatus(obj[7].toString());
				msb.setOrgName(obj[8].toString());
				msb.setValidStartDate(obj[9].toString());
				msb.setValidEndDate(obj[10].toString());
				tempList.add(msb);
			}
	 }
	 searchRsList=tempList;
	}
    
    private Operators dealSave(Operators tempOper,Operators oper){
    	tempOper.setOrgCode(oper.getOrgCode());
    	tempOper.setCardNo(oper.getCardNo());
    	tempOper.setCardType(oper.getCardType());
    	tempOper.setRoleType(oper.getRoleType());
    	tempOper.setTelphone(oper.getTelphone());
    	tempOper.setAddress(oper.getAddress());
    	tempOper.setEmail(oper.getEmail());
    	tempOper.setRemark(oper.getRemark());
    	tempOper.setSex(oper.getSex());
    	tempOper.setMobile(oper.getMobile());
    	tempOper.setRealName(oper.getRealName());
    	tempOper.setShortName(oper.getShortName());
    	return tempOper;
    }
    
    
    @Action(value = "queryAgentInit", results = { @Result(name = "success", location = "/pages/profit_share/profit_share_detail_choise.jsp")
    })
	public String queryAgentInit() throws Exception{
	    try{
			org();
		}catch (Exception e) {
		// TODO: handle exception
		addActionError("加载代理商信息异常");
		logger.error(e.getMessage(),e);
		}
			
	   return SUCCESS;
    }
	
	@Action(value = "queryAgentList", 
			results = { @Result(name = "success", location = "/pages/profit_share/profit_share_detail_choise.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryAgentList() throws Exception{
       
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		
		if(searchCondition==null){
			searchCondition=(OperatorQuerySearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new OperatorQuerySearchCondition();
			}
		}
		try {
			
			org();
			//searchCondition.setRoleType(Role.AGENT.getCode());
			if(Role.AGENT.getCode().equals(logingOperators.getRoleType()) || Role.O_MANAGER.getCode().equals(logingOperators.getRoleType())){//代理商
				 List<Operators> opList=merchantServices.listAllSubMerchants(logingOperators.getId());
				 agentList= new String[opList.size()];
				 for (int i=0;i<opList.size();i++) {
					 
					Operators o=opList.get(i);
					agentList[i]=Long.toString(o.getId());
					
				}
				 searchCondition.setAgentId(agentList);
			}
			
			
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			}
			dealWithTheListSpecially(searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return SUCCESS;
	}

	public List<ProfitPercent> getNewPreList(List<ProfitPercent> perList){
		List<ProfitPercent> perListNew  = new ArrayList<ProfitPercent>();
		for (ProfitPercent per : perList) {
			String percentStr = per.getPercent();
			Double perDouble = Double.parseDouble(percentStr) * 100;
			// double 转 int 类型,便于页面显示
			BigDecimal b = new BigDecimal(perDouble);
			int percent = b.intValue();
			
			per.setPercent(percent + "");
			perListNew.add(per);
		}
		return perListNew;
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_BEAN_OPRATOR_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BEAN_OPRATOR_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public OperatorQuerySearchCondition getSearchConditon() {
		return searchCondition;
	}

	public void setSearchConditon(OperatorQuerySearchCondition searchConditon) {
		this.searchCondition = searchCondition;
	}



	public List<TblInsInf> getOrgList() {
		return orgList;
	}
	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}
	public Operators getOper() {
		return oper;
	}

	public void setOper(Operators oper) {
		this.oper = oper;
	}
	public OperatorQuerySearchCondition getSearchCondition() {
		return searchCondition;
	}
	public void setSearchCondition(OperatorQuerySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public Map<String, String> getRoleList() {
		return roleList;
	}
	public void setRoleList(Map<String, String> roleList) {
		this.roleList = roleList;
	}
	public String getAccountNo() {
		return accountNo;
	}
	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}
	public Operators getAgent() {
		return agent;
	}
	public void setAgent(Operators agent) {
		this.agent = agent;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public List<TblArea> getAreaList() {
		return areaList;
	}
	public void setAreaList(List<TblArea> areaList) {
		this.areaList = areaList;
	}
	public String getAgentTo() {
		return agentTo;
	}
	public void setAgentTo(String agentTo) {
		this.agentTo = agentTo;
	}
	public String getAreaId() {
		return areaId;
	}
	public void setAreaId(String areaId) {
		this.areaId = areaId;
	}
}
